<script setup>
import _ from 'lodash';
import {useCommonStore} from "@jzl/stores";
import {onMounted, ref, watch} from "vue";
import {$WinMicrosvc} from "@jzl/comps-mg";
import {api} from "@jzl/api";
import {DFT_ICONS} from "@jzl/icons";

const DEFAULT_FORM = {
  content_type: 'PER_FORM',
  content_name: "",
  content_code: "",
  content_desc: "",
  icon: { icon: '', image: '', color: '' },
  form_id: -1,
  flow_id: -1,
  is_default_menu: 0,
  is_white_menu: 0,

  form: {form_id: '', form_name: ''},
  view: {form_view_id: '', view_name: ''},
  page_id: null,
  page: {page_id: '', page_name: ''},
  report: {},
  api: {}
}

const emit = defineEmits([ 'success', 'cancel' ]);
const props = defineProps({
  actionType: {
    type: String,
    default: 'view'
  },
  currentData: {
    type: Object,
    default: () => {
    }
  },
  tty: {
    type: String,
    default: null
  },
  appId: {
    type: Number,
    default: null
  }
})

const loading = ref(false)
const form = ref(_.cloneDeep(DEFAULT_FORM))
const formRef = ref(null)

onMounted(() => {
  init()
})

watch(() => [props.actionType, props.currentData], () => {
  init()
}, { deep: true })

const init = () => {
  let iForm = null;

  if (props.actionType === 'createPermission') {
    iForm = _.defaults({
      project_id: useCommonStore().project?.project_id,
      content_group_id: _.get(props.currentData, 'group_id', props.appId) || -1,
      content_name: "",
      content_code: "",
      content_desc: "",
      tty: props.tty,
      form_id: -1,
      is_default_menu: 0,
      form: null,
      view: null,
      flow: null,
      page_id: null,
      page: null
    }, DEFAULT_FORM);
  } else {
    iForm = _.cloneDeep(props.currentData);

    if (!iForm.icon) {
      iForm.icon = { icon: '', color: '', image: '' };
    } else if (_.isString(iForm.icon)) {
      iForm.icon = { icon: iForm.icon, color: '', image: '' };
    }

    if(!iForm.icon.icon && iForm.icon.iconfont) {
      iForm.icon.icon = iForm.icon.iconfont;
    }
  }

  form.value = iForm;
}

const handleSubmitCreateMenu = async () => {
  let data = _.cloneDeep(form.value);
  let id = _.get(data, 'content_id');
  let ret = null;

  // 系统菜单，编码不能为空
  if (!data.content_code) {
    data.content_code = $utils.getNanoid()
  }

  if (id) {
    ret = await api.menu.updateMenu(id, data);
  } else {
    ret = await api.menu.createMenu(data);
  }

  if (!ret) return;

  let tid = _.get(form.value, 'tid') || `c_${_.get(ret, 'content_id')}`;

  loading.value = false;
  $jui.toast('操作成功！');

  emit('success', tid);
}

const handleShowFormSelectWin = () => {
  $WinForms({
    type: 'view',
    onSelect: (info) => {
      let form = _.get(info, 'form');
      let view = _.get(info, 'view');
      if (!form || !form.form_id) return;

      form.value.form_id = form.form_id;
      form.value.form = form;
      form.value.view = view;
      form.value.view_id = _.get(view, 'form_view_id', -1);
      // this.$set(form.value, 'form', form);
      // this.$set(form.value, 'view', view);

      let formName = _.get(form, 'form_name');
      let viewName = _.get(view, 'view_name');
      let name = formName;

      if (viewName) name += `-${viewName}`;

      if (!form.value.content_name) form.value.content_name = name;
    }
  });
}

const handleShowReport = async () => {
  $WinReports({
    onSelect: async (report) => {
      let reportdef_code = _.get(report, 'reportdef_code');
      let reportdef_id = _.get(report, 'reportdef_id');

      if (!reportdef_id || !reportdef_code) return;

      form.value.report_id = reportdef_id;
      form.value.report = report;
      // this.$set(this.form, 'report', report);

      let reportName = _.get(report, 'title');

      if (!form.value.content_name) form.value.content_name = reportName;
    }
  });
}

const handleShowApi = async () => {
  $WinMicrosvc({
    onConfirm: async (api) => {
      let api_uuid = _.get(api, 'api_uuid');

      if (!api_uuid) return;

      form.value.api_uuid = api_uuid;
      form.value.api = api;
      // this.$set(form.value, 'api', api);

      let apiName = _.get(api, 'api_name');

      if (!form.value.content_name) form.value.content_name = apiName;
    }
  });
}

const handleCancelEdit = () => {
  emit('cancel');
}

const viewLabel = (view) => {
  return (view && view.view_name) || '默认';
}
</script>


<template>
  <el-form
    ref="formRef"
    label-width="100px"
  >
    <el-form-item label="权限名">
      <el-input
        v-model="form.content_name"
        placeholder="权限名称，如：新增用户"
        :disabled="actionType === 'view'"
      ></el-input>
    </el-form-item>
    <el-form-item label="权限类型">
      <!-- 暂时放开，应该默认菜单不能修改类型 -->
      <el-radio-group
        v-model="form.content_type"
        :disabled="actionType === 'view'"><!-- || actionType == 'edit' -->
        <el-radio label="PER_FORM">表单类</el-radio>
        <!--<el-radio label="PER_PAGE">页面类</el-radio>-->
        <el-radio label="PER_REPORT">报表</el-radio>
        <el-radio label="PER_API">微接口</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="表单" v-if="form.content_type === 'PER_FORM'">
      <template v-if="actionType !== 'view'">
        <el-tag
          v-if="form.form && form.form.form_id"
          size="medium" style="margin-right: 10px;">
          {{ form.form.form_name }}
          <JIcon :icon="DFT_ICONS.braceLeft" />{{ viewLabel(form.view) }}<JIcon :icon="DFT_ICONS.braceRight" /></el-tag>
        <el-button type="primary" @click="handleShowFormSelectWin" size="mini">选择表单</el-button>
      </template>
      <template v-else-if="form.form">
        <el-tag size="medium">
          {{ form.form.form_name }}
          <JIcon :icon="DFT_ICONS.braceLeft"/>
          {{ viewLabel(form.view) }}
          <JIcon :icon="DFT_ICONS.braceRight"/>
        </el-tag>
      </template>
    </el-form-item>
    <el-form-item label="页面" v-else-if="form.content_type === 'PER_PAGE'">
      <el-tag
        v-if="form.page && form.page.page_id" size="medium"
        @click="handleShowPagePreview(form.page)"
        style="margin-right: 10px;cursor:pointer;">{{ form.page.page_name }}
      </el-tag>
      <template v-if="actionType != 'view'">
        <el-button
          type="primary"
          @click="handleShowPageSelectWin"
        >选择页面
        </el-button>
      </template>
    </el-form-item>
    <el-form-item label="报表" v-else-if="form.content_type === 'PER_REPORT'">
      <el-tag
        v-if="form.report && form.report.reportdef_id"
        size="medium"
        style="margin-right: 10px;cursor:pointer;">{{ form.report.title }}
      </el-tag>
      <template
        v-if="actionType !== 'view'">
        <el-button
          type="primary"
          @click="handleShowReport">选择报表
        </el-button>
      </template>
    </el-form-item>

    <el-form-item label="微接口" v-else-if="form.content_type === 'PER_API'">
      <el-tag
        v-if="form.api && form.api.api_uuid"
        size="medium"
        style="margin-right: 10px;cursor:pointer;">{{ form.api.api_name }}
      </el-tag>
      <template
        v-if="actionType !== 'view'">
        <el-button
          type="primary"
          @click="handleShowApi"
        >选择微接口
        </el-button>
      </template>
    </el-form-item>

    <!--<el-form-item label="描述">
        <el-input type="textarea" :rows="2" v-model="form.content_desc" :disabled="actionType == 'view'"></el-input>
    </el-form-item>-->
    <el-form-item
      label=""
      v-if="actionType !== 'view'">
      <el-button
        size="default"
        type="primary"
        @click="handleSubmitCreateMenu()"> 提交
      </el-button>
      <el-button
        size="default"
        @click="handleCancelEdit()"> 取消
      </el-button>
    </el-form-item>
  </el-form>
</template>
